<template>
	<div class="app-container">
		<!-- 搜索和新增区域 -->
		<el-card>
			<el-row :gutter="20">
				<el-col :span="6">
					<el-select
						v-model="queryParams.cycleType"
						placeholder="周期类型"
						clearable
						@change="handleSearch"
						style="width: 100%"
					>
						<el-option
							v-for="item in cycleTypeOptions"
							:key="item.dictValue"
							:label="item.dictLabel"
							:value="item.dictValue"
						/>
					</el-select>
				</el-col>
				<el-col :span="6">
					<el-select
						v-model="queryParams.shiftRotationRule"
						placeholder="班次轮换规则"
						clearable
						@change="handleSearch"
						style="width: 100%"
					>
						<el-option
							v-for="item in shiftRotationRuleOptions"
							:key="item.dictValue"
							:label="item.dictLabel"
							:value="item.dictValue"
						/>
					</el-select>
				</el-col>
				<el-col :span="12" style="text-align: right"> </el-col>
			</el-row>
		</el-card>

		<!-- 周期机制表格 -->
		<el-card class="mt-1">
			<el-button type="primary" @click="showAddDialog" icon="Plus"
				>新增周期机制</el-button
			>
			<el-table
				class="mt-2"
				:data="cycleMechanismList"
				border
				style="width: 100%"
				v-loading="loading"
				:cell-style="{ textAlign: 'center' }"
				:header-cell-style="{ textAlign: 'center', fontWeight: 'bold' }"
			>
				<el-table-column prop="cycleName" label="周期名称" align="center" />
				<el-table-column prop="cycleType" label="周期类型" align="center">
					<template #default="{ row }">
						{{ getDictLabel(cycleTypeOptions, row.cycleType) }}
					</template>
				</el-table-column>
				<el-table-column prop="startDate" label="起始日期" align="center" />
				<el-table-column prop="endDate" label="结束日期" align="center" />
				<el-table-column prop="cycleLength" label="周期时长" align="center" />
				<el-table-column
					prop="shiftRotationRule"
					label="班次轮换规则"
					align="center"
				>
					<template #default="{ row }">
						{{ getDictLabel(shiftRotationRuleOptions, row.shiftRotationRule) }}
					</template>
				</el-table-column>
				<el-table-column
					prop="employeeAssignmentRule"
					label="员工分配规则"
					align="center"
				>
					<template #default="{ row }">
						{{
							getDictLabel(
								employeeAllocationRuleOptions,
								row.employeeAssignmentRule
							)
						}}
					</template>
				</el-table-column>
				<el-table-column prop="isActive" label="状态" align="center">
					<template #default="{ row }">
						<el-tag :type="row.isActive === 1 ? 'success' : 'danger'">
							{{ row.isActive === 1 ? "已激活" : "未激活" }}
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="操作" align="center" fixed="right">
					<template #default="scope">
						<el-button size="small" @click="handleEdit(scope.row)"
							>编辑</el-button
						>
						<el-button
							size="small"
							type="danger"
							@click="handleDelete(scope.row)"
							>删除</el-button
						>
					</template>
				</el-table-column>
			</el-table>

			<!-- 分页 -->
			<div class="mt-2">
				<el-pagination
					v-model:current-page="queryParams.pageNum"
					v-model:page-size="queryParams.pageSize"
					:page-sizes="[10, 20, 50, 100]"
					layout="total, sizes, prev, pager, next, jumper"
					:total="total"
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
				/>
			</div>
		</el-card>

		<!-- 新增周期机制对话框 -->
		<el-dialog
			v-model="addDialogVisible"
			title="新增周期机制"
			width="50%"
			:close-on-click-modal="false"
		>
			<el-form
				:model="addForm"
				label-width="120px"
				:rules="rules"
				ref="addFormRef"
			>
				<el-form-item label="周期名称" prop="cycleName">
					<el-input v-model="addForm.cycleName" placeholder="请输入周期名称" />
				</el-form-item>
				<el-form-item label="周期类型" prop="cycleType">
					<el-select
						v-model="addForm.cycleType"
						placeholder="请选择周期类型"
						style="width: 100%"
					>
						<el-option
							v-for="item in cycleTypeOptions"
							:key="item.dictValue"
							:label="item.dictLabel"
							:value="item.dictValue"
						/>
					</el-select>
				</el-form-item>
				<el-form-item label="起始日期" prop="startDate">
					<el-date-picker
						v-model="addForm.startDate"
						type="date"
						placeholder="选择起始日期"
						style="width: 100%"
						value-format="YYYY-MM-DD"
					/>
				</el-form-item>
				<el-form-item label="结束日期" prop="endDate">
					<el-date-picker
						v-model="addForm.endDate"
						type="date"
						placeholder="选择结束日期"
						style="width: 100%"
						value-format="YYYY-MM-DD"
					/>
				</el-form-item>
				<el-form-item label="周期时长" prop="cycleLength">
					<el-input-number
						v-model="addForm.cycleLength"
						:min="1"
						style="width: 100%"
					/>
				</el-form-item>
				<el-form-item label="班次轮换规则" prop="shiftRotationRule">
					<el-select
						v-model="addForm.shiftRotationRule"
						placeholder="请选择班次轮换规则"
						style="width: 100%"
					>
						<el-option
							v-for="item in shiftRotationRuleOptions"
							:key="item.dictValue"
							:label="item.dictLabel"
							:value="item.dictValue"
						/>
					</el-select>
				</el-form-item>
				<el-form-item label="员工分配规则" prop="employeeAssignmentRule">
					<el-select
						v-model="addForm.employeeAssignmentRule"
						placeholder="请选择员工分配规则"
						style="width: 100%"
					>
						<el-option
							v-for="item in employeeAllocationRuleOptions"
							:key="item.dictValue"
							:label="item.dictLabel"
							:value="item.dictValue"
						/>
					</el-select>
				</el-form-item>
				<el-form-item label="是否激活" prop="isActive">
					<el-switch
						v-model="addForm.isActive"
						:active-value="1"
						:inactive-value="0"
						active-text="激活"
						inactive-text="未激活"
					/>
				</el-form-item>
				<el-form-item label="备注" prop="remark">
					<el-input
						v-model="addForm.remark"
						type="textarea"
						:rows="2"
						placeholder="请输入备注信息"
					/>
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="addDialogVisible = false">取消</el-button>
					<el-button type="primary" @click="confirmAdd">保存</el-button>
				</span>
			</template>
		</el-dialog>

		<!-- 编辑周期机制对话框 -->
		<el-dialog
			v-model="editDialogVisible"
			title="编辑周期机制"
			width="50%"
			:close-on-click-modal="false"
		>
			<el-form
				:model="editForm"
				label-width="120px"
				:rules="rules"
				ref="editFormRef"
			>
				<el-form-item label="周期名称" prop="cycleName">
					<el-input v-model="editForm.cycleName" placeholder="请输入周期名称" />
				</el-form-item>
				<el-form-item label="周期类型" prop="cycleType">
					<el-select
						v-model="editForm.cycleType"
						placeholder="请选择周期类型"
						style="width: 100%"
					>
						<el-option
							v-for="item in cycleTypeOptions"
							:key="item.dictValue"
							:label="item.dictLabel"
							:value="item.dictValue"
						/>
					</el-select>
				</el-form-item>
				<el-form-item label="起始日期" prop="startDate">
					<el-date-picker
						v-model="editForm.startDate"
						type="date"
						placeholder="选择起始日期"
						style="width: 100%"
						value-format="YYYY-MM-DD"
					/>
				</el-form-item>
				<el-form-item label="结束日期" prop="endDate">
					<el-date-picker
						v-model="editForm.endDate"
						type="date"
						placeholder="选择结束日期"
						style="width: 100%"
						value-format="YYYY-MM-DD"
					/>
				</el-form-item>
				<el-form-item label="周期时长" prop="cycleLength">
					<el-input-number
						v-model="editForm.cycleLength"
						:min="1"
						style="width: 100%"
					/>
				</el-form-item>
				<el-form-item label="班次轮换规则" prop="shiftRotationRule">
					<el-select
						v-model="editForm.shiftRotationRule"
						placeholder="请选择班次轮换规则"
						style="width: 100%"
					>
						<el-option
							v-for="item in shiftRotationRuleOptions"
							:key="item.dictValue"
							:label="item.dictLabel"
							:value="item.dictValue"
						/>
					</el-select>
				</el-form-item>
				<el-form-item label="员工分配规则" prop="employeeAssignmentRule">
					<el-select
						v-model="editForm.employeeAssignmentRule"
						placeholder="请选择员工分配规则"
						style="width: 100%"
					>
						<el-option
							v-for="item in employeeAllocationRuleOptions"
							:key="item.dictValue"
							:label="item.dictLabel"
							:value="item.dictValue"
						/>
					</el-select>
				</el-form-item>
				<el-form-item label="是否激活" prop="isActive">
					<el-switch
						v-model="editForm.isActive"
						:active-value="1"
						:inactive-value="0"
						active-text="激活"
						inactive-text="未激活"
					/>
				</el-form-item>
				<el-form-item label="备注" prop="remark">
					<el-input
						v-model="editForm.remark"
						type="textarea"
						:rows="2"
						placeholder="请输入备注信息"
					/>
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="editDialogVisible = false">取消</el-button>
					<el-button type="primary" @click="confirmEdit">保存</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup>
	import { ref, reactive, onMounted } from "vue";
	import { ElMessage, ElMessageBox } from "element-plus";
	import {
		getCycleTypeList,
		getShiftRotationRuleList,
		getEmployeeAllocationRuleList,
		getCycleMechanismList,
		getCycleMechanismDetail,
		addCycleMechanism,
		updateCycleMechanism,
		deleteCycleMechanism,
	} from "@/api/prod_operate/sys_setting/prod_run/cycle_setup";

	// 加载状态
	const loading = ref(false);

	// 下拉选项数据
	const cycleTypeOptions = ref([]);
	const shiftRotationRuleOptions = ref([]);
	const employeeAllocationRuleOptions = ref([]);

	// 周期机制列表数据
	const cycleMechanismList = ref([]);

	// 总记录数
	const total = ref(0);

	// 查询参数
	const queryParams = reactive({
		pageNum: 1,
		pageSize: 10,
		cycleType: undefined,
		shiftRotationRule: undefined,
	});

	// 新增表单
	const addForm = reactive({
		cycleName: "",
		cycleType: "",
		startDate: "",
		endDate: "",
		cycleLength: 7,
		shiftRotationRule: "",
		employeeAssignmentRule: "",
		isActive: 1,
		remark: "",
	});

	// 编辑表单
	const editForm = reactive({
		cycleId: "",
		cycleName: "",
		cycleType: "",
		startDate: "",
		endDate: "",
		cycleLength: 7,
		shiftRotationRule: "",
		employeeAssignmentRule: "",
		isActive: 1,
		remark: "",
	});

	// 对话框控制
	const addDialogVisible = ref(false);
	const editDialogVisible = ref(false);

	// 表单引用
	const addFormRef = ref(null);
	const editFormRef = ref(null);

	// 表单验证规则
	const rules = reactive({
		cycleName: [{ required: true, message: "请输入周期名称", trigger: "blur" }],
		cycleType: [
			{ required: true, message: "请选择周期类型", trigger: "change" },
		],
		startDate: [
			{ required: true, message: "请选择起始日期", trigger: "change" },
		],
		endDate: [{ required: true, message: "请选择结束日期", trigger: "change" }],
		cycleLength: [
			{ required: true, message: "请输入周期时长", trigger: "blur" },
			{ type: "number", min: 1, message: "周期时长必须大于0", trigger: "blur" },
		],
		shiftRotationRule: [
			{ required: true, message: "请选择班次轮换规则", trigger: "change" },
		],
		employeeAssignmentRule: [
			{ required: true, message: "请选择员工分配规则", trigger: "change" },
		],
	});

	// 根据字典值获取标签
	const getDictLabel = (options, value) => {
		const item = options.find((item) => item.dictValue === value);
		return item ? item.dictLabel : value;
	};

	// 初始化数据
	const initData = async () => {
		try {
			loading.value = true;

			// 获取下拉选项数据
			const [cycleTypeRes, shiftRotationRuleRes, employeeAllocationRuleRes] =
				await Promise.all([
					getCycleTypeList(),
					getShiftRotationRuleList(),
					getEmployeeAllocationRuleList(),
				]);

			cycleTypeOptions.value = cycleTypeRes.data;
			shiftRotationRuleOptions.value = shiftRotationRuleRes.data;
			employeeAllocationRuleOptions.value = employeeAllocationRuleRes.data;

			// 获取周期机制列表
			await fetchCycleMechanismList();
		} catch (error) {
			console.error("初始化数据失败:", error);
			ElMessage.error("初始化数据失败");
		} finally {
			loading.value = false;
		}
	};

	// 获取周期机制列表
	const fetchCycleMechanismList = async () => {
		try {
			loading.value = true;
			const res = await getCycleMechanismList(queryParams);
			cycleMechanismList.value = res.rows;
			total.value = res.total;
		} catch (error) {
			console.error("获取周期机制列表失败:", error);
			ElMessage.error("获取周期机制列表失败");
		} finally {
			loading.value = false;
		}
	};

	// 处理搜索
	const handleSearch = () => {
		queryParams.pageNum = 1;
		fetchCycleMechanismList();
	};

	// 处理分页大小变化
	const handleSizeChange = (val) => {
		queryParams.pageSize = val;
		fetchCycleMechanismList();
	};

	// 处理当前页变化
	const handleCurrentChange = (val) => {
		queryParams.pageNum = val;
		fetchCycleMechanismList();
	};

	// 显示新增对话框
	const showAddDialog = () => {
		addForm.cycleName = "";
		addForm.cycleType = "";
		addForm.startDate = "";
		addForm.endDate = "";
		addForm.cycleLength = 7;
		addForm.shiftRotationRule = "";
		addForm.employeeAssignmentRule = "";
		addForm.isActive = 1;
		addForm.remark = "";
		addDialogVisible.value = true;
	};

	// 确认新增
	const confirmAdd = async () => {
		try {
			await addFormRef.value.validate();

			await addCycleMechanism(addForm);
			ElMessage.success("新增周期机制成功");
			addDialogVisible.value = false;
			fetchCycleMechanismList();
		} catch (error) {
			console.error("新增周期机制失败:", error);
			if (error.message) {
				ElMessage.error(error.message);
			}
		}
	};

	// 处理编辑
	const handleEdit = async (row) => {
		try {
			loading.value = true;
			const res = await getCycleMechanismDetail(row.cycleId);
			Object.assign(editForm, res.data);
			editDialogVisible.value = true;
		} catch (error) {
			console.error("获取周期机制详情失败:", error);
			ElMessage.error("获取周期机制详情失败");
		} finally {
			loading.value = false;
		}
	};

	// 确认编辑
	const confirmEdit = async () => {
		try {
			await editFormRef.value.validate();

			await updateCycleMechanism(editForm);
			ElMessage.success("修改周期机制成功");
			editDialogVisible.value = false;
			fetchCycleMechanismList();
		} catch (error) {
			console.error("修改周期机制失败:", error);
			if (error.message) {
				ElMessage.error(error.message);
			}
		}
	};

	// 处理删除
	const handleDelete = (row) => {
		ElMessageBox.confirm("确认删除该周期机制吗?", "提示", {
			confirmButtonText: "确定",
			cancelButtonText: "取消",
			type: "warning",
		})
			.then(async () => {
				try {
					await deleteCycleMechanism(row.cycleId);
					ElMessage.success("删除成功");
					fetchCycleMechanismList();
				} catch (error) {
					console.error("删除周期机制失败:", error);
					ElMessage.error("删除失败");
				}
			})
			.catch(() => {
				// 取消删除
			});
	};

	// 初始化
	onMounted(() => {
		initData();
	});
</script>

<style scoped>
	.app-container {
		padding: 20px;
	}

	.el-pagination {
		margin-top: 20px;
		text-align: right;
	}

	.el-select {
		width: 100%;
	}

	.el-table {
		margin-top: 20px;
	}

	.el-date-editor {
		width: 100%;
	}
</style>
